<template>
  <div class="admin-layout">
    <!-- 顶部导航 -->
    <el-header class="admin-header">
      <div class="header-left">
        <h2>FAIR plus机器人全产业链接会管理系统</h2>
      </div>
      <div class="header-right">
        <el-dropdown @command="handleUserCommand">
          <span class="user-info">
            <el-avatar :size="32" :src="userInfo.avatar">
              {{ userInfo.username.charAt(0).toUpperCase() }}
            </el-avatar>
            <span class="username">{{ userInfo.username }}</span>
            <el-icon><ArrowDown /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <!-- <el-dropdown-item command="profile">个人资料</el-dropdown-item> -->
              <el-dropdown-item command="settings">系统设置</el-dropdown-item>
              <el-dropdown-item divided command="logout"
                >退出登录</el-dropdown-item
              >
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </el-header>

    <div class="admin-container">
      <!-- 左侧菜单 -->
      <el-aside class="admin-sidebar" :width="sidebarWidth">
        <el-menu
          :default-active="activeMenu"
          class="admin-menu"
          :collapse="isCollapse"
          @select="handleMenuSelect"
        >
          <template v-for="menu in userMenus" :key="menu.path || menu.title">
            <!-- 一级菜单 -->
            <el-menu-item
              v-if="menu.path && !menu.children"
              :index="menu.path"
              :disabled="!hasPermission(menu.permission)"
            >
              <el-icon><component :is="menu.icon" /></el-icon>
              <template #title>{{ menu.title }}</template>
            </el-menu-item>

            <!-- 二级菜单 -->
            <el-sub-menu v-else-if="menu.children" :index="menu.title">
              <template #title>
                <el-icon><component :is="menu.icon" /></el-icon>
                <span>{{ menu.title }}</span>
              </template>
              <el-menu-item
                v-for="subMenu in menu.children"
                :key="subMenu.path"
                :index="subMenu.path"
                :disabled="!hasPermission(subMenu.permission)"
              >
                <el-icon><component :is="subMenu.icon" /></el-icon>
                <template #title>{{ subMenu.title }}</template>
              </el-menu-item>
            </el-sub-menu>
          </template>
        </el-menu>
      </el-aside>

      <!-- 主内容区 -->
      <el-main class="admin-main">
        <div class="breadcrumb">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item>FAIR plus管理系统</el-breadcrumb-item>
            <el-breadcrumb-item v-for="item in breadcrumbs" :key="item.path">
              {{ item.title }}
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>

        <div class="content-wrapper">
          <router-view />
        </div>
      </el-main>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, onBeforeMount } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { ArrowDown } from "@element-plus/icons-vue";
import { isAdminTokenValid, adminLogout } from "@/utils/auth";

export default {
  name: "AdminLayout",
  components: {
    ArrowDown,
  },
  setup() {
    const router = useRouter();
    const route = useRoute();

    const isCollapse = ref(false);
    const sidebarWidth = computed(() => (isCollapse.value ? "64px" : "200px"));

    // 用户信息
    const userInfo = reactive({
      id: 1,
      username: "admin",
      role: "super_admin",
      avatar: "",
      permissions: ["all"],
    });

    // 菜单配置
    const menuConfig = {
      super_admin: [
        {
          path: "/admin/dashboard",
          title: "仪表盘",
          icon: "DataBoard",
          permission: "dashboard",
        },
        {
          path: "/admin/homepage",
          title: "首页管理",
          icon: "House",
          permission: "homepage_manage",
        },
        {
          path: "/admin/about",
          title: "关于我们",
          icon: "Document",
          permission: "about_manage",
        },
        {
          title: "展商管理",
          icon: "OfficeBuilding",
          children: [
            {
              path: "/admin/exhibitors",
              title: "展商信息",
              icon: "OfficeBuilding",
              permission: "exhibitor_manage",
            },
            {
              path: "/admin/products",
              title: "产品管理",
              icon: "Box",
              permission: "product_manage",
            },
            {
              path: "/admin/exhibitor-content",
              title: "展商中心内容",
              icon: "Document",
              permission: "exhibitor_content_manage",
            },
          ],
        },
        {
          title: "观众管理",
          icon: "Avatar",
          children: [
            {
              path: "/admin/visitors",
              title: "观众信息",
              icon: "Avatar",
              permission: "visitor_manage",
            },
            {
              path: "/admin/visitor-content",
              title: "观众中心内容",
              icon: "Document",
              permission: "visitor_content_manage",
            },
            {
              path: "/admin/group-visit",
              title: "团体信息维护",
              icon: "Document",
              permission: "visitor_manage",
            },
            {
              path: "/admin/visa",
              title: "签证管理",
              icon: "Document",
              permission: "visa_manage",
            },
            // { path: '/admin/tickets', title: '票务管理', icon: 'Ticket', permission: 'ticket_manage' }
          ],
        },
        {
          title: "活动管理",
          icon: "Calendar",
          children: [
            {
              path: "/admin/activities",
              title: "活动日历信息",
              icon: "Calendar",
              permission: "activity_manage",
            },
            {
              path: "/admin/activity-content",
              title: "活动中心内容",
              icon: "Document",
              permission: "activity_content_manage",
            },
          ],
        },
        {
          title: "媒体管理",
          icon: "VideoCamera",
          children: [
            {
              path: "/admin/media-info",
              title: "媒体信息",
              icon: "Document",
              permission: "media_manage",
            },
            {
              path: "/admin/media-regitser",
              title: "媒体注册信息",
              icon: "Document",
              permission: "media_manage",
            },
            {
              path: "/admin/media",
              title: "媒体中心内容管理",
              icon: "Document",
              permission: "media_manage",
            },
          ],
        },
        {
          path: "/admin/downloads",
          title: "下载管理",
          icon: "Download",
          permission: "download_manage",
        },
        {
          title: "系统管理",
          icon: "Setting",
          children: [
            {
              path: "/admin/users",
              title: "用户管理",
              icon: "User",
              permission: "user_manage",
            },
            {
              path: "/admin/contacts",
              title: "联系人设置",
              icon: "User",
              permission: "system_setting",
            },
            // { path: '/admin/permissions', title: '权限管理', icon: 'Lock', permission: 'permission_manage' },
            // { path: '/admin/menus', title: '菜单管理', icon: 'Menu', permission: 'menu_manage' },
            {
              path: "/admin/settings",
              title: "系统设置",
              icon: "Setting",
              permission: "system_setting",
            },
          ],
        },
      ],
      admin: [
        {
          path: "/admin/dashboard",
          title: "仪表盘",
          icon: "DataBoard",
          permission: "dashboard",
        },
        {
          path: "/admin/homepage",
          title: "首页管理",
          icon: "House",
          permission: "homepage_manage",
        },
        {
          path: "/admin/about",
          title: "关于我们",
          icon: "Document",
          permission: "about_manage",
        },
        {
          path: "/admin/approvals",
          title: "审核管理",
          icon: "Check",
          permission: "approval_manage",
        },
        {
          title: "展商管理",
          icon: "OfficeBuilding",
          children: [
            {
              path: "/admin/exhibitors",
              title: "展商信息",
              icon: "OfficeBuilding",
              permission: "exhibitor_manage",
            },
            {
              path: "/admin/products",
              title: "产品管理",
              icon: "Box",
              permission: "product_manage",
            },
            {
              path: "/admin/exhibitor-content",
              title: "展商中心内容",
              icon: "Document",
              permission: "exhibitor_content_manage",
            },
          ],
        },
        {
          title: "观众管理",
          icon: "Avatar",
          children: [
            {
              path: "/admin/visitors",
              title: "观众信息",
              icon: "Avatar",
              permission: "visitor_manage",
            },
            {
              path: "/admin/visitor-content",
              title: "观众中心内容",
              icon: "Document",
              permission: "visitor_content_manage",
            },
            {
              path: "/admin/group-visit",
              title: "团体信息维护",
              icon: "Document",
              permission: "visitor_manage",
            },
            {
              path: "/admin/visa",
              title: "签证管理",
              icon: "Document",
              permission: "visa_manage",
            },
            // { path: '/admin/tickets', title: '票务管理', icon: 'Ticket', permission: 'ticket_manage' }
          ],
        },
        {
          title: "活动管理",
          icon: "Calendar",
          children: [
            {
              path: "/admin/activities",
              title: "活动信息",
              icon: "Calendar",
              permission: "activity_manage",
            },
            {
              path: "/admin/activity-content",
              title: "活动中心内容",
              icon: "Document",
              permission: "activity_content_manage",
            },
          ],
        },
        {
          title: "媒体管理",
          icon: "VideoCamera",
          children: [
            {
              path: "/admin/media-info",
              title: "媒体信息",
              icon: "Document",
              permission: "media_manage",
            },
            {
              path: "/admin/media",
              title: "媒体中心内容管理",
              icon: "Document",
              permission: "media_manage",
            },
          ],
        },
        {
          path: "/admin/downloads",
          title: "下载管理",
          icon: "Download",
          permission: "download_manage",
        },
        {
          title: "系统管理",
          icon: "Setting",
          children: [
            {
              path: "/admin/users",
              title: "用户管理",
              icon: "User",
              permission: "user_manage",
            },
            {
              path: "/admin/contacts",
              title: "联系人设置",
              icon: "User",
              permission: "system_setting",
            },
            {
              path: "/admin/settings",
              title: "系统设置",
              icon: "Setting",
              permission: "system_setting",
            },
          ],
        },
      ],
      editor: [
        {
          path: "/admin/dashboard",
          title: "仪表盘",
          icon: "DataBoard",
          permission: "dashboard",
        },
        {
          title: "媒体管理",
          icon: "VideoCamera",
          children: [
            {
              path: "/admin/media-info",
              title: "媒体信息",
              icon: "Document",
              permission: "media_manage",
            },
            {
              path: "/admin/media",
              title: "媒体中心内容管理",
              icon: "Document",
              permission: "media_manage",
            },
          ],
        },
        {
          title: "活动管理",
          icon: "Calendar",
          children: [
            {
              path: "/admin/activities",
              title: "活动信息",
              icon: "Calendar",
              permission: "activity_manage",
            },
            {
              path: "/admin/activity-content",
              title: "活动中心内容",
              icon: "Document",
              permission: "activity_content_manage",
            },
          ],
        },
        {
          path: "/admin/downloads",
          title: "下载管理",
          icon: "Download",
          permission: "download_manage",
        },
      ],
    };

    // 根据用户角色获取菜单
    const userMenus = computed(() => {
      return menuConfig[userInfo.role] || menuConfig.editor;
    });

    // 当前激活的菜单
    const activeMenu = computed(() => {
      // 检查是否在子菜单中
      for (const menu of userMenus.value) {
        if (menu.children) {
          const subMenu = menu.children.find((sub) => sub.path === route.path);
          if (subMenu) {
            return route.path;
          }
        }
      }
      return route.path;
    });

    // 面包屑导航
    const breadcrumbs = computed(() => {
      // 查找当前菜单（包括子菜单）
      let currentMenu = null;
      let parentMenu = null;

      for (const menu of userMenus.value) {
        if (menu.path === route.path) {
          currentMenu = menu;
          break;
        }
        if (menu.children) {
          const subMenu = menu.children.find((sub) => sub.path === route.path);
          if (subMenu) {
            currentMenu = subMenu;
            parentMenu = menu;
            break;
          }
        }
      }

      if (currentMenu) {
        if (parentMenu) {
          return [
            { path: parentMenu.title, title: parentMenu.title },
            { path: route.path, title: currentMenu.title },
          ];
        } else {
          return [{ path: route.path, title: currentMenu.title }];
        }
      }
      return [];
    });

    // 权限检查
    const hasPermission = (permission) => {
      if (!permission) return true; // 如果没有权限要求，则允许访问
      if (userInfo.permissions.includes("all")) return true;
      return userInfo.permissions.includes(permission);
    };

    // 菜单选择
    const handleMenuSelect = (path) => {
      router.push(path);
    };

    // 用户操作
    const handleUserCommand = async (command) => {
      switch (command) {
        case "profile":
          router.push("/admin/profile");
          break;
        case "settings":
          router.push("/admin/settings");
          break;
        case "logout":
          try {
            await ElMessageBox.confirm("确定要退出登录吗？", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            });

            // 清除登录状态
            localStorage.removeItem("adminToken");
            localStorage.removeItem("adminUser");

            ElMessage.success("退出成功");
            router.push("/admin/login");
          } catch {
            // 用户取消
          }
          break;
      }
    };

    onMounted(() => {
      // 检查登录状态
      const token = localStorage.getItem("adminToken");
      const user = localStorage.getItem("adminUser");

      if (!token || !user) {
        router.push("/admin/login");
        return;
      }

      // 检查token是否有效
      if (!isAdminTokenValid()) {
        ElMessage.error("登录已过期，请重新登录");
        adminLogout();
        return;
      }

      try {
        const userData = JSON.parse(user);
        Object.assign(userInfo, userData);
      } catch (error) {
        console.error("解析用户信息失败:", error);
        ElMessage.error("用户信息异常，请重新登录");
        adminLogout();
      }
    });

    onBeforeMount(() => {
      const lang = localStorage.getItem("user_lang");
      if (lang === "english") {
        window.translate.changeLanguage("chinese_simplified");
        window.translate.selectLanguageTag.languages = "chinese_simplified";
      }
    });

    return {
      isCollapse,
      sidebarWidth,
      userInfo,
      userMenus,
      activeMenu,
      breadcrumbs,
      hasPermission,
      handleMenuSelect,
      handleUserCommand,
    };
  },
};
</script>

<style scoped>
.admin-layout {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.admin-header {
  background: linear-gradient(135deg, #320063 0%, #4a0a8a 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.header-left h2 {
  margin: 0;
  font-size: 20px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
  cursor: pointer;
  padding: 5px 10px;
  border-radius: 5px;
  transition: background-color 0.3s;
}

.user-info:hover {
  background: rgba(255, 255, 255, 0.1);
}

.username {
  font-size: 14px;
}

.admin-container {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.admin-sidebar {
  background: white;
  border-right: 1px solid #e6e6e6;
  box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
}

.admin-menu {
  border: none;
  height: 100%;
}

.admin-menu .el-sub-menu .el-menu-item {
  padding-left: 40px;
}

.admin-menu .el-sub-menu .el-menu-item .el-icon {
  margin-right: 8px;
}

.admin-menu .el-sub-menu .el-sub-menu__title {
  font-weight: 500;
}

.admin-menu .el-sub-menu .el-menu-item {
  font-size: 13px;
}

.admin-menu .el-sub-menu .el-menu-item:hover {
  background-color: #f0f9ff;
}

.admin-main {
  background: #f8f9fa;
  padding: 20px;
  overflow-y: auto;
}

.breadcrumb {
  margin-bottom: 20px;
  padding: 15px;
  background: white;
  border-radius: 5px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.content-wrapper {
  background: white;
  border-radius: 10px;
  min-height: calc(100vh - 200px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

@media (max-width: 768px) {
  .admin-sidebar {
    position: fixed;
    z-index: 1000;
    height: 100vh;
    transform: translateX(-100%);
    transition: transform 0.3s;
  }

  .admin-sidebar.show {
    transform: translateX(0);
  }

  .admin-main {
    margin-left: 0;
  }
}
</style>
